<template>
  <div style="height:100%;">
    
  <div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <i class="el-icon-setting"></i> 系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{$route.meta.displayName}}</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

   
  <el-row :gutter="10">
    <el-col :span="24">
      <ul id="menuZTree" class="ztree"></ul>
      <div id="rMenu" class="dropdown dropdown-preview">
        <ul class="dropdown-menu">
          <li id="m_add">
            <!-- <a {{action "addTreeNode" 'menuZTree'}}>增加菜单</a> -->
            <a @click = "addTreeNode">增加菜单</a>
          </li>
          <li id="m_del">
            <!-- <a {{action "removeTreeNode" 'menuZTree'}}>删除菜单</a> -->
  
            <a @click = "removeTreeNode">删除菜单</a>
  
          </li>
          <li id="m_modify">
            <!-- <a {{action "modifyTreeNode" 'menuZTree'}}>修改菜单</a> -->
            <a @click = "modifyTreeNode">修改菜单</a>
          </li>
        </ul>
      </div>
    </el-col>

  </el-row>
  <el-dialog :title="dialogTitle" @close="handledialogClose" v-model="dialogMenuOperateVisible" class="demo-box demo-ruleForm">
    <el-row type="flex" class="row-bg" justify="center">
      <el-col :span="24">
        <el-form :model="selectMenuDataForm" :rules="menuDataValidateRules" ref="selectMenuDataForm">
          <el-form-item prop="name" label-position="right" label="名称:" :label-width="formLabelWidth">
            <el-input v-model="selectMenuDataForm.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="icon" label-position="right" label="图标:" :label-width="formLabelWidth">
            <el-input v-model="selectMenuDataForm.icon" auto-complete="off"></el-input>
          </el-form-item>
  
          <el-form-item prop="displayName" label-position="right" label="路由路径:" :label-width="formLabelWidth">
            <el-input v-model="selectMenuDataForm.displayName" auto-complete="off"></el-input>
          </el-form-item>
  
          <el-form-item prop="params" :disabled="true" label-position="right" label="执行参数:" :label-width="formLabelWidth">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="selectMenuDataForm.params">
            </el-input>
          </el-form-item>
  
          <el-form-item prop="authIndex" label-position="right" label="序号:" :label-width="formLabelWidth">
            <!-- <el-input v-model="selectMenuDataForm.authIndex" auto-complete="off"></el-input> -->
            <el-input-number v-model="selectMenuDataForm.authIndex" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item prop="authType" label-position="right" label="菜单类型:" :label-width="formLabelWidth">
            <el-select v-model="selectMenuDataForm.authType" disabled placeholder="请选择菜单类型">
              <el-option label="导航菜单" value="1"></el-option>
              <el-option label="场景菜单" value="2"></el-option>
            </el-select>
          </el-form-item>
  
          <el-form-item label="是否有效" label-position="right" :label-width="formLabelWidth" prop="active">
            <el-switch on-text="是" off-text="否" v-model="selectMenuDataForm.active"></el-switch>
          </el-form-item>
          <el-form-item label="是否只读" label-position="right" :label-width="formLabelWidth" prop="readOnly">
            <el-switch on-text="是" off-text="否" v-model="selectMenuDataForm.readOnly"></el-switch>
          </el-form-item>
  
          <el-form-item prop="sence" :disabled="true" label-position="right" label="场景:" :label-width="formLabelWidth">
            <el-input v-model="selectMenuDataForm.sence" auto-complete="off"></el-input>
          </el-form-item>
  
          <el-form-item prop="parentSelfName" label-position="right" label="父菜单:" :label-width="formLabelWidth">
            <el-input :disabled="true" v-model="selectMenuDataForm.parentSelfName" auto-complete="off"></el-input>
          </el-form-item>
  
          <el-form-item prop="note" label-position="right" label="备注:" :label-width="formLabelWidth">
            <el-input v-model="selectMenuDataForm.note" auto-complete="off"></el-input>
          </el-form-item>
  
        </el-form>
      </el-col>
    </el-row>
    <div slot="footer" v-if="dialogTitle=='菜单修改'" class="dialog-footer">
      <el-button @click="handleCancelSubmitForm('selectMenuDataForm')">取 消</el-button>
      <el-button type="primary" @click="handleModifyMenuDataActionForm('selectMenuDataForm')">保存</el-button>
    </div>
     <div slot="footer" v-else class="dialog-footer">
      <el-button @click="handleCancelSubmitForm('selectMenuDataForm')">取 消</el-button>
      <el-button type="primary" @click="handleModifyMenuDataActionForm('selectMenuDataForm')">确定</el-button>
    </div>
  </el-dialog>

  </div>
</template>
<script>
import MenuService from 'api/security/menu';
import { Loading } from 'element-ui';
let id = 0;
export default {

  data: function () {
    return {
      
      zTreeSetting: {},
      zTreeNodes: [],
      //menuTree DATA
      dialogMenuOperateVisible: false,
      dialogTitle: '新增菜单',
      selectMenuDataForm:{
        name: '',
        displayName: '',//路由名称
        icon: '',
        authIndex: '',
        parentSelf: '',
        parentSelfName: '',
        authType: "",
        active: false, //有效
        readOnly: false, //只读
        note: '', //备注
        params: '',//执行参数
        sence: ''//场景
      },
      formLabelWidth: '30%',// label 宽度
      menuDataValidateRules: {
        name: [{
          required: true,
          message: '菜单名称不能为空',
          trigger: 'blur'
        }]
      },
    }
  },
  methods: {
    handleCancelSubmitForm(formName) {
      this.dialogMenuOperateVisible = false;
    },
    handledialogClose(ev) {
      this.dialogMenuOperateVisible = false;
      this.selectMenuDataForm = {
        name: '',
        displayName: '',//路由名称
        icon: '',//图标样式
        authIndex: '',//序号
        parentSelf: null,
        parentSelfName: '',
        authType: "",//菜单类型，1=导航菜单，2=对象功能菜单
        active: false, //是否有效，0=无效，1=有效
        readOnly: false, //是否只读菜单，0=否，1=是
        note: '', //备注
        params: '',//执行参数
        sence: '',//场景
        loadType: ''//菜单加载方式。1=jquery.load方式，2=iframe方式，3=新开window方式

      };

    },
    addTreeNode:function (){
      //获取到选中的节点
      var treeObj = $.fn.zTree.getZTreeObj("menuZTree");
      var selectNodes = treeObj.getSelectedNodes();

      console.log(selectNodes);
      //关闭 右键菜单，并弹出 对话框
      this.hiddenRMenu();
      this.dialogTitle = '新增菜单';
      this.dialogMenuOperateVisible = true ;

      if (selectNodes == null || selectNodes.length == 0){
        //根元素
        this.selectMenuDataForm.parentSelf = null ;
      }

      if (selectNodes.length  == 1 ){
        //子元素
        //获取到父级元素的名字
        var node = selectNodes[0];
    
        this.selectMenuDataForm.parentSelf = node.id ;
        this.selectMenuDataForm.parentSelfName =  node.name;
      }
      
    },
    removeTreeNode:function (){
      //根据id 去删除
      var self = this ;
      var treeObj = $.fn.zTree.getZTreeObj("menuZTree");
      var selectNodes = treeObj.getSelectedNodes();
      if (selectNodes.length == 0 ){
         self.$message({
            type: 'info',
            message: '请选择要删除的菜单'
          });
          return ;
      }
      if (selectNodes.length == 1){
        //获取到id
        var data = selectNodes[0];
        var confirmInfo = "此操作将删除菜单:" + data.name + ", 是否继续?";
        var self = this;
        if (data.children != null && data.children.length > 0) {
          self.$message({
            type: 'info',
            message: '请先删除子菜单'
          });
          return ;
        } else {
          this.$confirm(confirmInfo, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var params = { id: data.id };
            MenuService.delMenuData(params).then(response => {
              if (response.data) {
                self.$message({
                  type: 'success',
                  message: '删除成功'
                });
                
                treeObj.removeNode(selectNodes[0]);

              }
            }).catch(err => {
              self.$message({
                type: 'error',
                message: '删除失败'
              });
            });

          }).catch(() => {
            self.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

        }
      }
      

    },

    modifyTreeNode:function (){
      //弹出dialog 用户填写信息
      //点击保存按钮 
      var treeObj = $.fn.zTree.getZTreeObj("menuZTree");
      var selectNodes = treeObj.getSelectedNodes();
       if (selectNodes.length == 1){
        //关闭 右键菜单，并弹出 对话框
        this.hiddenRMenu();
        this.dialogTitle = "菜单修改" ;
        this.dialogMenuOperateVisible = true ;
        let menu = selectNodes[0] ;
        if (menu.parentSelf!=null && menu.parentSelf!=""){
          let node = treeObj.getNodeByTId(menu.parentTId);
          menu.parentSelfName = node.name ;
        }
        this.selectMenuDataForm = menu;
        
      }else{
        self.$message({
           type: 'info',
           message: '请选择需要更改的菜单项'
         });
      }
    },
    
    handleModifyMenuDataActionForm(formName) {
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let tparams = self.selectMenuDataForm;
          let msg ='';
          console.log(self.dialogTitle);
          if (self.dialogTitle == '新增菜单') {
            delete tparams.id;// 如果是新菜单 删除id 属性
            msg = '新增成功!';
          }else {
            msg = '修改成功!';
          }
          MenuService.saveMenuData(tparams).then(response => {
            if (response.data != null && response.data.errorCode == null) {
              self.$message({
                type: "success",
                message: msg
              });
              //刷新 tree
              let newNode =  response.data
               
              var treeObj = $.fn.zTree.getZTreeObj("menuZTree");
              if (self.dialogTitle == '新增菜单'){
                treeObj.addNodes(treeObj.getSelectedNodes()[0], newNode);
              }else{
                treeObj.getSelectedNodes()[0] = newNode ;
                treeObj.updateNode(treeObj.getSelectedNodes()[0]);
              }
             
             
              //关闭dialog
              self.dialogMenuOperateVisible = false;

              

            }
          }).catch(err => {

          });
        }
      });
    },
    //隐藏右键菜单
    hiddenRMenu() {
      var rMenu = $("#rMenu");
      if (rMenu) rMenu.css({ "visibility": "hidden" });
      $("body").unbind("mousedown", onBodyMouseDown);
      function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
          rMenu.css({ "visibility": "hidden" });
        }
      }
    },
    //显示右键菜单
    showRMenu(type, x, y) {
      $("#rMenu ul").show();
      if (type == "root") {
        $("#m_del").hide();
        $("#m_modify").hide();
      } else {
        $("#m_del").show();
         $("#m_modify").show();
      }
      var rMenu = $("#rMenu");
      rMenu.css({ "top": y + "px", "left": x + "px", "visibility": "visible" });

    },

    /**
         * 初始化下MenuZTreeSetting 的事件
         */
    _initMenuZTreeSetting: function () {
      var self = this ;
  
      var zTreeSetting = {
        view: {
          selectedMulti: false,//禁止多选
          showIcon:false
        },
        callback: {
          //选中事件
          beforeClick: function (treeId, treeNode, clickFlag) {
            //右侧的面板中显示所选中的treeNode 的属性值！
            self.hiddenRMenu();
          },
          //右键事件
          onRightClick: function (event, treeId, treeNode) {
            var zTreeObj = $.fn.zTree.getZTreeObj(treeId);
            var rMenu = $("#rMenu");
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
              zTreeObj.cancelSelectedNode();
              self.showRMenu("root", event.clientX, event.clientY);
            
            } else if (treeNode && !treeNode.noR) {
              zTreeObj.selectNode(treeNode);
              self.showRMenu("node", event.clientX, event.clientY);
            }

            
          },
        }

      };
      this.zTreeSetting = zTreeSetting ;
    },

    _initZTree:function (){
     
      $.fn.zTree.init($("#menuZTree"),this.zTreeSetting,this.zTreeNodes);

     
    },
    _refreshZTree:function(){
      this._initZTree();
    },

    _expandAll: function (tag=true) {
      var treeObj = $.fn.zTree.getZTreeObj("menuZTree");
      treeObj.expandAll(tag);
    },
    queryAllMenus:function (){
      var _self = this;
     
      let loadingInstance =  Loading.service({ fullscreen: true,target:"ul#menuZTree" });
      MenuService.queryAllMenus().then((response) => {
        if (response.data.errorCode == null) {
          //获取到 菜单信息
          var tempMenuData = response.data;

          _self.zTreeNodes = tempMenuData;
          _self._refreshZTree();
           _self._expandAll(true);
           loadingInstance.close();
        } else {

        }
      }).catch(err => {

      });
    }


  },
  mounted: function () {
   
    this._initMenuZTreeSetting();
    this.queryAllMenus();
  }
}
</script>
<style scoped >
.el-row {
  margin-bottom: 20px;
}

.el-col .el-input {
  margin-bottom: 10px;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

i .el-icon-plus,
i .el-icon-edit,
i .el-icon-delete {
  color: rgba(255, 255, 255, 0.9)!important;
}

div #rMenu{
    position:fixed;
    visibility:hidden;
}


.dropdown-menu > li {
    /* float: left; */
    margin: 2px;
    vertical-align: top;
}
.dropdown-menu li > ul{
    list-style: none;
    padding: 0px 2px;
}
 .dropdown-menu li a{
   cursor:pointer;
 }
.dropdown-menu li a:HOVER,
.dropdown-menu li a:FOCUS,
.dropdown-menu li a:HOVER,
.dropdown-menu li a:FOCUS {
    background-color: #30a5ff;
    color: #ffffff;
}



/**菜单设置的横向展示end**/

</style>





